package com.quanyan.user.kafka.inbound;

import com.alibaba.fastjson.JSONObject;
import com.quanyan.comment.enums.TaskEnum;
import com.quanyan.user.constants.UserConstants;
import com.quanyan.user.mq.UserTaskMsg;
import com.quanyan.user.service.UserInviteService;
import com.quanyan.user.service.UserTaskService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 接收kafka发来的消息.
 */
public class UserTaskKafkaConsumer {

    private static final Logger logger = LoggerFactory.getLogger(UserTaskKafkaConsumer.class);

    @Autowired
    private UserTaskService userTaskService;



    //用户邀请主题
    @Value("${kafka.topic.user.register.invite}")
    private String userInviteTopic;

    @Value("${kafka.topic.userTask.c")
    private String userCenterUserTaskTopic;

    Pattern p = Pattern.compile("(\\d=)");

    public void distribute(Map map) {
        logger.info("开始处理 c++ 来自kafka的 消息------------》{}",map.toString());
        Iterator<String> iterator = map.keySet().iterator();

        while(iterator.hasNext()){
            String key = iterator.next();
            logger.info("消息的key：{}",key);
            logger.info("消息的value：{}",map.get(key).toString());
            if(UserConstants.USER_CENTER_KAFKA_C_USER_TASK.equals(key)){// 做任务
                Matcher m= p.matcher(map.get(key).toString());
                StringBuffer taskMsg = new StringBuffer();
                if(m.find()){
                    String tem = m.replaceAll("").toString();
                    taskMsg.append( tem.substring(1,tem.length()-1));
                }
                logger.info("消息是{}",taskMsg.toString());

                List<UserTaskMsg> lst =  JSONObject.parseArray(taskMsg.toString(), UserTaskMsg.class);
                if(lst == null || lst.size() < 1)
                    return;

                if( lst.size() == 1)
                    userTaskService.whileTask(lst.get(0).getUid(),lst.get(0).getTaskId());
                else
                    userTaskService.doActivityTask(lst);


//                for(UserTaskMsg u : lst){
//                    if(TaskEnum.TASK_ENUM__MOBILE.getId() == u.getTaskId().intValue()){
//                        logger.info("任务消息处理完毕，开始处理邀请好友");
//
//                        userInviteService.rewardUserRegister(u.getUid());
//                        logger.info("任务消息处理完毕，结束处理邀请好友");
//
//                    }
//                }

            }
        }
    }

}
